package com.qf.flash.mvp.presenter;

import android.text.TextUtils;

import com.hyphenate.easeui.utils.ChatUserCacheMgr;
import com.qf.dblib.dao.entity.ChatUser;
import com.qf.dblib.dao.entity.UserInfo;
import com.qf.dblib.dao.impl.UserMgr;
import com.qf.flash.constant.FlashCodes;
import com.qf.flash.event.UserUpdateEvent;
import com.qf.flash.http.HttpManager;
import com.qf.flash.mvp.contract.EditInformationContract;
import com.qf.flashlib.base.BasePresenter;
import com.qf.flashlib.base.BaseSubscriber;
import com.qf.flashlib.exception.ApiException;
import com.qf.flashlib.util.RxUtils;

import org.greenrobot.eventbus.EventBus;

import java.io.File;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

public class EditInformationPresenter extends BasePresenter<EditInformationContract.View> implements EditInformationContract.Presenter {
    private static final String TAG = "ep";

    @Override
    public void submitInfo(UserInfo info) {
        String photo = info.getPhoto();
        MultipartBody.Builder builder=new MultipartBody.Builder()
                .addFormDataPart("userId",info.getUid())
                .addFormDataPart("sex",info.getSex())
                .addFormDataPart("name",info.getName())
                .addFormDataPart("sign",info.getSign())
                .addFormDataPart("photoLine",info.getPhotoLine());
        if (!TextUtils.isEmpty(photo) && !photo.startsWith("http")) {
            File file = new File(photo);
            RequestBody fileRQ = RequestBody.create(MediaType.parse("multipart/form-data"), file);
            builder.addFormDataPart("imgFile", file.getName(), fileRQ);
        }
        addSubscription(HttpManager.getInstance().getGsonHttpApi()
                .UPDATE_USER(builder.build())
                .compose(RxUtils.handleResult())
                .compose(RxUtils.io_main())
                .subscribeWith(new BaseSubscriber<Object>(mRootView) {
                    @Override
                    public void onSuccess(Object o) {
                        mRootView.onSubmitSuccess();
                        info.setStatus(FlashCodes.STATUS_ONLINE);
                        UserMgr.getInstance().saveUser(info);
                        ChatUser chatUser = new ChatUser();
                        chatUser.setUid(info.getUid());
                        chatUser.setAvatar(info.getPhoto());
                        chatUser.setNick(info.getName());
                        ChatUserCacheMgr.getInstance().saveUser(chatUser);
                        EventBus.getDefault().post(new UserUpdateEvent());
                    }

                    @Override
                    public void onError(ApiException e) {
                        super.onError(e);
                        mRootView.onSubmitFailed();
                    }
                })
        );
    }
}
